package com.tjcd.project.library_base.base.network;


import com.hjq.gson.factory.GsonFactory;
import com.tjcd.project.library_base.common.basicInfor.SugarUrls;

import java.util.concurrent.TimeUnit;

import netpresenter.annotations.NetBuilder;
import netpresenter.iface.INetBuilder;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @Author jiangKunKun
 * @CreateDate 2021/7/7
 * @Description
 * @SpittingGrooves
 */
@NetBuilder
public class NetManager implements INetBuilder {

    public Retrofit mRetrofit;

    /**
     * 懒汉双重锁 创建实例
     * @return
     */
    public Retrofit getBaseRetrofit() {
        if (null == mRetrofit) {
            synchronized (NetManager.class){
                if (null == mRetrofit) {
                    mRetrofit = getBaseUrl();
                }
            }
        }
        return mRetrofit;
    }

    /**
     * 重置 Retrofit
     */
    public void resetRetrofit(){
        if (null != mRetrofit) {
            synchronized (NetManager.class){
                if (null != mRetrofit) {
                    mRetrofit = null;
                }
            }
        }
    }

    /**
     * 获取基础 Retrofit 对象
     * @return
     */
    public static Retrofit getBaseUrl() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        // 使用自定义的 SSLSocketFactory 和 X509TrustManager
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getTrustManager());
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier()); // 取消验证主机名
        // 取消验证
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        // 连接超时的时间
        builder.connectTimeout(30, TimeUnit.SECONDS);
        // 连接的读取超时时间
        builder.readTimeout(30, TimeUnit.SECONDS);
        // 写入超时时间
        builder.writeTimeout(30, TimeUnit.SECONDS);
        // 添加拦截器
//        builder.addInterceptor(new NetInterceptor());
        return new Retrofit.Builder()
                .baseUrl(SugarUrls.DEBUG ? SugarUrls.baseDeBugUrl : SugarUrls.baseUrl)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create(GsonFactory.getSingletonGson()))
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
    }

    @Override
    public <T> T create(Class<T> t) {
        return getBaseRetrofit().create(t);
    }
}
